<template>
  <div id="login">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" >
      <el-form-item prop="phone">
        <el-input type="text" v-model="ruleForm.phone" autocomplete="off" placeholder="手机号" ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off" placeholder="密码" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="logining">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {request,url} from '../../assets/request.js'
import {session} from '../../assets/session.js'
import qs from 'qs'
export default {
    data() {
      return {
        timer: null,  
        ruleForm: {
          phone: '',
          password: '',
        },
        rules: {
            phone: [{
                pattern:/^[\s\S]*.*[^\s][\s\S]*$/,
                required: true,
                message: '请输入正确的手机号',
                trigger: 'blur'
            }],
            password: [{
                pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
                required: true,
                message: '只能输入6-20个字母、数字、下划线',
                trigger: 'blur'
            }]
        }
      };
    },
    created(){
        session('del','topNav');  //清空头部导航数组
        session('del','leftActive');  //清空当前的导航选中状态
    },
    mounted(){
      this.getCookie()
    },
    methods: {
      logining() {
        // let arr=[]
        // arr=JSON.stringify(arr)
        // session('set','topNav',arr);  //头部导航数组
        // session('set','leftActive','1-1');  //当前的导航选中状态
        // this.$router.push({ path: '/index' })
        this.$refs.ruleForm.validate((valid) => {
          if(valid){
            let user=this.ruleForm;
            let name=user.phone;
            let pass=user.password;
            //保存coolie
            this.setCookie(name, pass, 7);
            var urls =url+ 'login';
            this.$http({
                  url: urls,
                  method: 'POST',
                  // 请求体重发送的数据
                  data:qs.stringify({
                      username: name,
                      password: pass,
                  }),
                  // 设置请求头
                  headers: {
                      'Content-Type': 'application/x-www-form-urlencoded'
                  }
              })
              .then(res => {
                  var code = res.data.code
                  if (code == 200) {
                      let arr=[]
                      arr=JSON.stringify(arr)
                      session('set','topNav',arr);  //头部导航数组
                      session('set','leftActive','1');  //当前的导航选中状态
                      session('set','user',JSON.stringify(res.data.data));
                      console.log(res.data.data)
                      this.option('登录成功正在为你跳转请稍后...', 'success');
                      this.getCode();
                  } else {
                      this.option("用户名不存在或密码错误,请重新输入");
                  }
              })
              .catch(err => {
                  // console.log(err)
              })
          }
        })
      },
      option(test, status) { 
          this.$message({
              message: test,
              type: status ? status : 'warning'
          })
        },
        getCode() {
            const TIME_COUNT = 1;
            if (!this.timer) {
                this.count = TIME_COUNT;
                this.show = false;
                this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                    } else {
                        this.show = true;
                        clearInterval(this.timer);
                        this.timer = null;
                        this.$router.push({ path: '/index' })
                    }
                }, 1000)
            }
        },
      //设置cookie
        setCookie(c_name, c_pwd, exdays) {
            var exdate = new Date(); //获取时间
            exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
            //字符串拼接cookie
            window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
            window.document.cookie = "password" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
        },
        //读取cookie
        getCookie: function() {
            if (document.cookie.length > 0) {
                var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
                for (var i = 0; i < arr.length; i++) {
                    var arr2 = arr[i].split('='); //再次切割
                    //判断查找相对应的值
                    if (arr2[0] == 'userName') {
                        this.ruleForm.phone = arr2[1]; //保存到保存数据的地方
                    } else if (arr2[0] == 'password') {
                        this.ruleForm.password = arr2[1];
                    }
                }
            } 
        },
        //清除cookie
        clearCookie: function() {
            this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
            // this.ruleForm.rememberMe = false;
        },
    }
  }
</script>
<style lang='less' scoped>
#login {
  width: 100%;
  background: #ffffff;
  padding:40px 40px 30px 40px;
  box-sizing: border-box;
  border-radius: 5px;
  .el-button{
    width:100%;
  }
}
</style>
<style lang="less">
@import "./Login.less";
</style>


